package com.jiuhao.service;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jiuhao.entity.KnowledgeDocument;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@RequiredArgsConstructor
@Slf4j
public class ElasticsearchService {

    private static final String INDEX_NAME = "unit8_knowledge_dev_doc_offline_2";
    private final RestHighLevelClient elasticsearchClient;
    private final ObjectMapper objectMapper;

    /**
     * 向Elasticsearch添加数据
     *
     * @param document 要添加的文档对象
     * @return 新增文档的ID
     * @throws IOException 如果操作Elasticsearch时发生错误
     */
    public String addDocument(KnowledgeDocument document) throws IOException {
        // 将实体对象转换为JSON字符串
        String jsonDocument = objectMapper.writeValueAsString(document);

        // 创建索引请求
        IndexRequest indexRequest = new IndexRequest(INDEX_NAME)
                .source(jsonDocument, XContentType.JSON);

        // 如果指定了ID，则使用指定的ID，否则由Elasticsearch自动生成
        if (document.getId() != null && !document.getId().isEmpty()) {
            indexRequest.id(document.getId());
        }

        // 执行索引请求
        IndexResponse indexResponse = elasticsearchClient.index(indexRequest, RequestOptions.DEFAULT);

        // 返回新增文档的ID
        return indexResponse.getId();
    }


}

